/**
 * 用户控制器
 * 处理用户相关的HTTP请求
 */

import * as userService from '../services/userService.js';
import { AppError } from '../utils/appError.js';

/**
 * 注册新用户
 * POST /api/v1/users/register
 */
export const register = async (req, res, next) => {
  try {
    const { username, password, gradeLevel } = req.body;

    // 调用服务层
    const result = await userService.register(username, password, gradeLevel);

    // 返回成功响应（包含token和用户信息）
    res.status(201).json({
      success: true,
      data: result,
      message: '注册成功',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 用户登录
 * POST /api/v1/users/login
 */
export const login = async (req, res, next) => {
  try {
    const { username, password } = req.body;

    // 调用服务层
    const result = await userService.login(username, password);

    // 返回成功响应
    res.status(200).json({
      success: true,
      data: result,
      message: '登录成功',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户信息（通过ID）
 * GET /api/v1/users/:userId
 */
export const getUserById = async (req, res, next) => {
  try {
    const { userId } = req.params;

    // 调用服务层
    const user = await userService.getUserById(userId);

    // 返回成功响应
    res.status(200).json({
      success: true,
      data: user,
      message: '获取用户信息成功',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户信息（通过用户名）
 * GET /api/v1/users/username/:username
 */
export const getUserByUsername = async (req, res, next) => {
  try {
    const { username } = req.params;

    // 调用服务层
    const user = await userService.getUserByUsername(username);

    // 返回成功响应
    res.status(200).json({
      success: true,
      data: user,
      message: '获取用户信息成功',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新用户资料
 * PUT /api/v1/users/:userId
 */
export const updateProfile = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const updates = req.body;

    // 调用服务层
    const user = await userService.updateProfile(userId, updates);

    // 返回成功响应
    res.status(200).json({
      success: true,
      data: user,
      message: '更新用户资料成功',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除用户
 * DELETE /api/v1/users/:userId
 */
export const deleteUser = async (req, res, next) => {
  try {
    const { userId } = req.params;

    // 调用服务层
    await userService.deleteUser(userId);

    // 返回成功响应
    res.status(200).json({
      success: true,
      message: '删除用户成功',
    });
  } catch (error) {
    next(error);
  }
};

